<?php

namespace app\admin\controller\card;

use think\Config;
use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use think\App;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use function Sodium\randombytes_random16;

/**
 * 卡密列管理
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{


    protected $dataLimit = 'auth';

    /**
     * Index模型对象
     * @var \app\admin\model\card\Index
     */
    protected $model = null;
    /**
     * @var \think\Model|null
     */
    private $admin;

    public function _initialize()
    {
        parent::_initialize();
        $this->admin = model("\app\admin\model\Admin")->get($this->auth->id);
        $this->model = new \app\admin\model\card\Index;

        // 优惠策略
        $discountArr = Config::get('site.discount');
        $this->view->assign("discountArr", $discountArr);
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['apps', 'admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','code','day','status','apply_date','createtime','apps_id', 'account', 'qq']);
                $row->visible(['apps']);
				$row->getRelation('apps')->visible(['name','domain']);
                $row->visible(['admin']);
                $row->getRelation('admin')->visible(['username']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function add()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        // 基础卡费
        $price = $this->auth->getGroups()[0]['price'];

        if ($this->request->isAjax()) {
            $params = $this->request->post("row/a");
            $validate = $this->validate($params, [
                "apps_id" => "require",
                "day" => "require|number|egt:0",
                'number' => "require|number|elt:9999|egt:0",
            ], [
                "apps_id.require"   => "请选择一个应用",
                "day.require"       => "请输入卡密有效天数",
                "day.number"        => "卡密天数必须为整数",
                "day.egt"           => "卡密天数必须大于0",
                "number.require"    => "卡密生成数量不能为空",
                "number.number"     => "卡密生成数量必须为整数",
                "number.elt"        => "卡密生成数量不能大于9999",
                "number.egt"        => "卡密生成数量必须大于0"
            ]);


            // 检查
            $app = model('\app\admin\model\card\Apps')->where('id', $params['apps_id'])->find();
            if (!$app) {
                $this->error("应用不存在");
            }

            if (!$this->auth->isSuperAdmin()) {
                $admins = explode(',', $app->admin_ids);
                if (!in_array($this->auth->id, $admins)) {
                    $this->error("您没有生成权限");
                }
            }

            if (true !== $validate) {
                $this->error($validate);
            }

            // 优惠策略
            $discountArr = Config::get('site.discount');
            $discount = 0;
            if ($discountArr && count($discountArr) > 0) {
                // 寻找最优优惠
                foreach ($discountArr as $day => $value) {
                    if ($params['day'] >= $day) {
                        $discount = $value;
                    }
                }
            }

            // 生成总价格
            $sum = $discount > 0 ? ($params['number'] * $price * $params['day']) * $discount : $params['number'] * $price * $params['day'];


            // 账户余额
            $balance = $this->admin['balance'];

            if ($sum > $balance) {
                $this->error("账户余额不足{$sum}元");
            }

            $cards = [];
            for ($i = 0; $i < $params['number']; $i ++) {
                try {
                    $card = sprintf("%s-%s-%s", bin2hex(random_bytes(6)), bin2hex(random_bytes(3)) , bin2hex(random_bytes(6)));
                    $cards[] = [
                        "day"   => $params['day'],
                        "apps_id"  => $params['apps_id'],
                        "code"  => strtoupper($card),
                        "admin_id" => $this->auth->id,
                        "createtime"   => time()
                    ];
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
            }

            $balance = $balance - $sum;

            // 启动事务
            Db::startTrans();
            try {
                // 更新余额
                Db::table('fa_admin')->where('id', $this->auth->id)->update(['balance' => $balance]);
                // 添加卡密
                Db::table('fa_card')->insertAll($cards);
                // 添加日志
                Db::table('fa_card_details')->insert([
                    "admin_id"  => $this->auth->id,
                    "amount"    => $params['number'],
                    "sum"       => $sum,
                    "price"     => $price,
                    "balance"   => $balance
                ]);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error("生成失败{$e->getMessage()}");
            }

            $this->success("生成成功");
        }

        $this->view->assign('price', $price);
        return $this->view->fetch();
    }



    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();

        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            if ($row->getAttr('status') == 1) {
                $this->error("卡密已经被激活，禁止编辑");
            }
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
